package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceIpml implements AddressBookService {

    @Autowired
    AddressBookMapper addressBookMapper;
    /**
     * 查询所有地址
     * @return
     */
    public List<AddressBook> list() {
        List<AddressBook> list = addressBookMapper.list(BaseContext.getCurrentId());
        return list;

    }

    /**
     * 添加地址
     * @param addressBook
     */
    public void addAddress(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.addAddress(addressBook);

    }

    /**
     * 设置默认地址
     * @param addressBook
     */
    public void setDefault(AddressBook addressBook) {
        //查找该用户有无已设置的默认地址
        List<AddressBook> list = addressBookMapper.findByIsDefault(BaseContext.getCurrentId());
        //判断是否已存在
        if(list.size() > 0 && list != null) {
            //将已有的默认状态设为0
            list.get(0).setIsDefault(0);
            addressBookMapper.setDefault(list.get(0));
        }
        //直接设置默认状态
        addressBook.setIsDefault(1);
        addressBookMapper.setDefault(addressBook);
    }



    /**
     * 根据id查询地址
     * @param id
     */
    public AddressBook findById(Long id) {
        AddressBook addressBook = addressBookMapper.findById(id);
        return addressBook;
    }

    /**
     * 修改地址
     * @param addressBook
     */
    public void updateAddress(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.update(addressBook);
    }

    /**
     * 删除地址
     * @param addressBook
     */
    public void deleteAddress(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.delete(addressBook);
    }

    /**
     *
     * @return
     */
    public AddressBook getDefaultAddress() {
        List<AddressBook> list = addressBookMapper.findByIsDefault(BaseContext.getCurrentId());
        return list.get(0);
    }


}
